/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/6/28 14:29
 */
package com.gitee.mechanic.json.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 将BigDecimal格式化为2位小数点
 *
 * @author mechanic
 * @version 0.0.1
 */
public class Decimal2Serializer extends JsonSerializer<BigDecimal> {

    //private DecimalFormat decimalFormat = new DecimalFormat("#.00");

    /**
     * Method that can be called to ask implementation to serialize
     * values of type this serializer handles.
     *
     * @param value       Value to serialize; can <b>not</b> be null.
     * @param gen         Generator used to output resulting Json content
     * @param serializers Provider that can be used to get serializers for
     */
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers)
      throws IOException, JsonProcessingException {
        gen.writeString(value.setScale(2, RoundingMode.HALF_UP).toPlainString());
//        gen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    }
}
